package components.photoLayer
{
	import SEApp.se_sapp;
	import SEApp.se_util;
	
	import UIFree.ObjectEvent;
	import UIFree.components.uif_window;
	import UIFree.controls.uif_button;
	import UIFree.controls.uif_popupMenu;
	import UIFree.uif_component;
	import UIFree.uif_loader;
	
	import UIPhoto.uip_events;
	
	import classes.clt_events;
	import classes.clt_images;
	import classes.clt_plugins;
	
	import components.clt_arrowB;
	import components.clt_component;
	import components.clt_plButton;
	import components.clt_popupMenu;
	import components.photo.clt_curUserAvatar;
	import components.photo.clt_photoEditor;
	import components.photoTools.clt_photoTools;
	
	import data.cd_defaults;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	
	public class clt_photoLayer extends clt_component {
		private var _pe: clt_photoEditor;
		private var _pt: clt_photoTools;
		private var _isDefaultPhoto: Boolean;
		private var maskID: uint;
		
		public function clt_photoLayer(parent	: uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0, styleClass:String='') {
			super(parent, ax, ay, awidth, aheight, styleClass);
			app.dispatchEvent(new ObjectEvent(se_sapp.REGSTARTCOMPONENT, this));
			var inner: Rectangle = getInner();
			_pe = new clt_photoEditor(this, clt_images, inner.x, inner.y, inner.width, inner.width * 1.20, 'photoEditor');
			_pe.addEvent(uip_events.UPDATEMATRIX, doUpdatePhoto);
			_pe.addEvent(MouseEvent.ROLL_OVER, function(e: Event): void {
				_pt.show();
			});
			
			_pe.addEvent(MouseEvent.ROLL_OUT, function(e: Event): void {
				_pt.hide();
			});
			
			_pt = new clt_photoTools(_pe, inner.x - 37, inner.y);
			
			addEvent(clt_events.UPDATEWORKSPACE, doUpdateWorkspace, workspace);
			addEvent(clt_events.LOADPHOTOCOMPLETE, doStartComplete, workspace);
			inner.y = inner.y + _pe.height;
			inner.height = clt_arrowB.DEFAULTHEIGHT;
			addButtonSubmenu('Коррекция/плагины', inner, [
				{caption: ' Коррекция цвета лица ', method	: doFaceColor}
			].concat(clt_plugins.menuList), doMenuPlugin, doFaceColor);
//			addButton('Коррекция цвета лица', doFaceColor, inner);
//			addButton('Выбрать фото из альбома', doPhotoSelect, inner);
//			addButton('Загрузить фото', doPhotoLoad, inner);
//			clt.photoSelectMenu

			var loadPhotoButton: clt_plButton = addButtonSubmenu('Загрузить фото', inner, clt.photoSelectMenu.list, 
												doLoadPhoto, this[clt.photoSelectMenu.def]);
			addButton('Выбрать вырез', doCutoutSelect, inner);
			addButton('Мои коллажи', doMyAlbumSelect, inner);
/*			
			addButtonSubmenu('Мои коллажи', inner, [
				{caption: ' Добавить в мой альбом ', method	: doBackgroundSelect},
				{caption: ' Загрузить с компьютера ', method	: doLoadBackground}
			], doMyAlbumSubmenu, doMyAlbumSelect);
*/			
				
//			addButton('Мой альбом', doCutoutSelect, inner);
			addButtonSubmenu('Фон', inner, [
				{caption: ' Выбрать из библиотеки фонов ', method	: doBackgroundSelect},
				{caption: ' Загрузить с компьютера ', method	: doLoadBackground}
			], doMenuSelect, doBackgroundSelect);
//			addButton('Выбрать фон', doBackgroundSelect, inner);
			var sml: Array = clt.saveMenuList;
			if (sml.length > 0)
				addButtonSubmenu('Сохранить/Отправить', inner, sml, doMenuSelect, function(e: Event): void {
					sml[0].method();
				}, 'saveB');
			
			addEvent(clt_events.DEAFULTTMPL, function(e: Event): void {
				loadPhotoButton.blink(3);
			}, workspace);
			
			new clt_curUserAvatar(this);
		}
		
		private function doMyAlbumSelect(e: Event): void {
			workspace.dispatchEvent(new Event(clt_events.SHOWMYCOLLAGES));
		}
		
		protected function doStartComplete(e: ObjectEvent): void {
			removeEvent(indexOfE(clt_events.LOADPHOTOCOMPLETE, doStartComplete, workspace));
			addEvent(clt_events.LOADPHOTOCOMPLETE, doLoadPhotoComplete, workspace);
			doLoadPhotoComplete(e);
			app.dispatchEvent(new ObjectEvent(se_sapp.STARTCOMPLETE, this));
		}
		
		protected function doWebCamera(e: Event): void {
			var camera	: Camera = Camera.getCamera();
            var window	: uif_window = null;
            var size	: Point = new Point(200, 200);
			var video	: Video;
            
            if (camera != null) {
	        	window = new clt.classes.dialog(clt.dialogLayer, 0, 0, size.x + 20, size.y + 50, false);
	        	window.title.text = 'Камера';
/*	        	window.x = (clt.topLayer.width - window.width) / 2;
	        	window.y = (clt.topLayer.height - window.height) / 2;*/
            	camera.setMode(600, 600, 8);
//                camera.addEventListener(ActivityEvent.ACTIVITY, activityHandler);
                video = new Video(camera.width, camera.height);
               	video.smoothing = true;
                video.attachCamera(camera);
                var inner: Rectangle = window.EnterHere(size);
                video.x = inner.x;
                video.y = inner.x;
                video.width		= inner.width;
                video.height	= inner.height;
                window.addEvent('CLOSEWINDOW', function(e: Event): void {
                	video.attachCamera(null);
                });
                
				clt_clothingBase.button(window, inner.x + (inner.width - 80) / 2, inner.y + inner.height - 10, 80, 33, 'Снимок', function(e: Event): void {
	        		var bmp: Bitmap = new Bitmap(new BitmapData(camera.width, camera.height, false), 'auto', true);
	        		bmp.bitmapData.draw(video);
					clt.workspace.dispatchEvent(new ObjectEvent(clt_events.LOADPHOTOCOMPLETE, bmp));
				});
			
                
/*                
	        	new clt.classes.button(window, inner.x + (inner.width - 80) / 2, inner.y + inner.height - 10, 80, 'Снимок', function(e: Event): void {
	        		var bmd: BitmapData = new BitmapData(camera.width, camera.height, false);
	        		bmd.draw(video);
	        		clt.photo.loadBytes(clt.encodeFromJPG(bmd));
	        	})*/
        	
                window.addChild(video);
                window.show();
            } else {
                clt.alert(clt.classes.data.WARNING, "Не выбрана веб-камера");
            }			
		}
		
		protected function doPhotoLoad(e: Event): void {
			clt.loadImage(clt_events.LOADPHOTOCOMPLETE, allFileFilters());
		}
		
		protected function allFileFilters(): Array {
			return [new FileFilter('JPEG формат', '*.jpg'),
				new FileFilter('PNG формат', '*.png'),
				new FileFilter('GIF формат', '*.gif'),
				new FileFilter('Любые файлы', '*.*')];
		}
		
		protected function doSave(e: Event): void {
			clt.saveMenuList[0].method();
		}
		
		protected function doLoadPhoto(e: ObjectEvent): void {
			this[e.object.method](e);
		}
		
		protected function doMenuSelect(e: ObjectEvent): void {
			e.object.method();
		}
		
		protected function doMenuPlugin(e: ObjectEvent): void {
			if (e.object.hasOwnProperty('method')) e.object.method();
			else clt_plugins.doMenuSelect(clt, e.object);
		}
		
		protected function doPhotoSelect(e: Event): void {
			workspace.dispatchEvent(new ObjectEvent(clt_events.SHOWTOOLS, 'photos'));
		}
		
		protected function doCutoutSelect(e: Event): void {
			workspace.dispatchEvent(new ObjectEvent(clt_events.SHOWTOOLS, 'cutouts'));
		}
		
		protected function doLoadBackground(e: Event=null): void {
			clt.loadImage(clt_events.LOADBACKGROUND, allFileFilters());
		}
		
		protected function doBackgroundSelect(e: Event=null): void {
			workspace.dispatchEvent(new ObjectEvent(clt_events.SHOWTOOLS, 'backgrounds'));
		}
		
		protected function doFaceColor(e: Event=null): void {
			workspace.dispatchEvent(new ObjectEvent(clt_events.SHOWTOOLS, 'correction'));
		}
		
		protected function doLoadPhotoComplete(e: ObjectEvent): void {
			_isDefaultPhoto = false;
			var loader: Loader = e.object as Loader;
			if (loader is uif_loader) {
				cd_defaults.startData.forEach(function(item: Object, i: int, arr: Array): void {
					if (item.image == (loader as uif_loader).sourceUrl) _isDefaultPhoto = true; 
				});
			}
			resetPhoto(loader?(se_util.bmpCopy(loader)):(e.object as Bitmap));
		}
		
		public function get isDefaultPhoto(): Boolean {
			return _isDefaultPhoto;
		}
		
		protected function resetPhoto(bmp: Bitmap): void {
			_pe.resetPhoto(bmp);
			_pe.photo.smoothing = true;
			_pe.refreshMask();
		}
		
		protected function doUpdatePhoto(e: ObjectEvent): void {
			workspace.dispatchEvent(new ObjectEvent(clt_events.UPDATEPHOTO, pe));
		}
		
		protected function doUpdateWorkspace(e: Event): void {
			if (workspace.maskInfo) {
				if (workspace.maskInfo.id != maskID) {
					 maskID = workspace.maskInfo.id;
					_pe.refreshMask();
				} else maskID = workspace.maskInfo.id;
			}
		}
		
		public function get pe(): clt_photoEditor {
			return _pe;
		}
	}
}